import { UploadOutlined } from '@ant-design/icons'
import { Alert, Button, Upload } from 'antd'

import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { message } from '@/utils/antdHelper'

/**
 * @typedef {Object} ImportModalProps
 * @property {string} [templateUrl] 模板地址
 * @property {() => Promise<any>} [startUpload] 开始导入
 */

/**
 * @param {ImportModalProps} props
 * @returns
 */
const ImportModal = props => {
  const { limitFileNum = 1, templateUrl, startUpload } = props
  const [form] = AekForm.useForm()
  const filePath = AekForm.useWatch('filePath', form)

  const onOk = async () => {
    const values = await form.validateFields()
    const { filePath } = values
    if (filePath.length > limitFileNum) {
      message.warning('一次只能导入一个文件')
      return Promise.reject()
    }
    const file = filePath[0].originFileObj
    await startUpload(file)
  }

  return (
    <AekModal width={650} title='导入数据' onOk={onOk}>
      <div className='mb16px'>
        <Alert type='warning' showIcon message='提示：请注意按导入模版格式填写，不符合要求的字段值将无法导入。' />
      </div>
      <AekForm
        form={form}
        formData={[
          {
            label: '导入文件',
            field: 'filePath',
            col: 18,
            formItemProps: {
              rules: [{ required: true, message: '请选择文件' }],
              valuePropName: 'fileList',
              getValueFromEvent: obj => {
                const { fileList = [] } = obj
                return fileList
              },
            },
            component: (
              <Upload
                disabled={filePath && filePath.length > limitFileNum}
                // 导入功能不用实际上传，form能拿到file对象就行
                beforeUpload={() => {
                  return false
                }}
                showUploadList
              >
                <Button disabled={filePath && filePath.length > limitFileNum} style={{ width: 300 }}>
                  <UploadOutlined /> 选择本地文件
                </Button>
              </Upload>
            ),
          },
          {
            col: 6,
            component: <a href={templateUrl}>【导入模板下载】</a>,
          },
        ]}
      />
    </AekModal>
  )
}

/** @type {(props?: import("@/components/AekModal").PromiseThenProps & ImportModalProps) => Promise<any>} */
ImportModal.PromiseThen = PromiseThen

export default ImportModal
